package com.zipou.myFax;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import com.zipou.myFax.Exception.FaxInitException;
import com.zipou.myFax.Exception.MailServiceException;
import com.zipou.myFax.common.FaxServiceImpl;
import com.zipou.myFax.mail.MailServiceImpl;

public class MyFax {

	private MailServiceImpl mail;
	private FaxServiceImpl fax;

	private Logger log;

	private Properties config;

	private static final String CONFIG_FILE_LOCATION = "/etc/myFax/myFax.conf";
//	private static final String CONFIG_FILE_LOCATION = "D://myFax.conf";

	public MyFax() {
		config = new Properties();
		try {
			config.load(new FileInputStream(MyFax.CONFIG_FILE_LOCATION));
			// init the logger
			initLogger();

			// instancing mailService
			mail = new MailServiceImpl(this);

			// launching the checking Thread to Pop Mails
			mail.start();

			// instancing FaxService
			fax = new FaxServiceImpl(this);
		} catch (FileNotFoundException e) {
			System.out.println("Config file not found at "
					+ MyFax.CONFIG_FILE_LOCATION);
		} catch (IOException e) {
			System.out.println("Couldn't open " + MyFax.CONFIG_FILE_LOCATION);
		} catch (LoggerException e) {
			System.out.println("Couldn't initiate the logger "
					+ MyFax.CONFIG_FILE_LOCATION);
		} catch (MailServiceException e) {
			this.getLogger().severe(
					"Ouch, MailServiceException: " + e.getMessage());
		} catch (FaxInitException e) {
			this.getLogger().severe(
					"Ouch, FaxServiceException: " + e.getMessage());
		} finally  {
			//L'initialisation n'a pas reussi... Je quitte le programme
			System.out.println("Exiting...");
			System.exit(1);
		}
	}

	public final Logger getLogger() {
		return log;
	}

	public final FaxServiceImpl getFax() {
		return fax;
	}

	private void initLogger() throws LoggerException {

		Handler fh = null;
		try {
			fh = new FileHandler(this.getProperty("LOG_FILE"));
			fh.setFormatter(new SimpleFormatter());
			log = Logger.getLogger("MyFax");
			log.addHandler(fh);
		} catch (Exception e) {
			throw new LoggerException(e.getMessage());
		}

	}

	public final String getProperty(String key)  {
		String tmp;
		tmp = this.config.getProperty(key);
		if (tmp == null) {
			this.getLogger().severe("Missing Key '" + key + "' in Config File");
			System.exit(1);
		}
		return tmp;
	}

	public static void main(String[] args) {
		new MyFax();

	}

}
